#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>

#define Convert(addr_ptr) ((struct sockaddr *)addr_ptr)

namespace Net_Work
{
    const static int defaultsockfd = -1;
    const int backlog = 5;
    enum
    {
        SocketError = 1,
        BindError,
        ListenError
    };

    // 封装一个基类，Socket接口类
    // 设计模式：模版方法类
    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void CreateSocketorDie() = 0;
        virtual void BindSocketorDie(uint16_t port) = 0;
        virtual void ListenSocketorDie(int backlog) = 0;
        virtual int AcceptConnection(std::string *peerip, uint16_t *peerport) = 0;
        virtual bool ConnectServer(const std::string &serverip, u_int16_t serverport) = 0;
        virtual int GetSockfd() = 0;
        virtual void SetSockfd(int sockfd) = 0;
        virtual void CloseSocket() = 0;
        virtual bool Recv(std::string *buffer, int size) = 0;
        virtual void Send(std::string &send_string) = 0;
        virtual void ReUseAddr() = 0;

    public:
        void BuildListensocketMethod(uint16_t port, int backlog) //  服务端
        {
            CreateSocketorDie();
            ReUseAddr();
            BindSocketorDie(port);
            ListenSocketorDie(backlog);
        }
        bool BuildConnectSocketMethod(const std::string &serverip, u_int16_t serverport) //  客户端
        {
            CreateSocketorDie();
            return ConnectServer(serverip, serverport);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = defaultsockfd)
            : _sockfd(sockfd)
        {
        }
        ~TcpSocket() {}

        void CreateSocketorDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                exit(SocketError);
            }
        }

        void BindSocketorDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;
            int n = ::bind(_sockfd, Convert(&local), sizeof(local));
            if (n < 0)
            {
                exit(BindError);
            }
        }

        void ListenSocketorDie(int backlog) override
        {
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
            {
                exit(ListenError);
            }
        }

        // 将连接该服务器的客户端的ip地址和port给带出来
        int AcceptConnection(std::string *peerip, uint16_t *peerport) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, Convert(&peer), &len);
            if (newsockfd < 0)
                return -1;
            *peerip = inet_ntoa(peer.sin_addr); // 网络序列转主机序列
            *peerport = ntohs(peer.sin_port);
            return newsockfd;
        }

        bool ConnectServer(const std::string &serverip, uint16_t serverport) override
        {
            struct sockaddr_in server;
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(serverip.c_str());
            server.sin_port = htons(serverport);
            int n = ::connect(_sockfd, Convert(&server), sizeof(server));
            if (n < 0)
                return false;
            else
                return true;
        }

        int GetSockfd() override
        {
            return _sockfd;
        }

        void SetSockfd(int sockfd) override
        {
            _sockfd = sockfd;
        }

        void CloseSocket() override
        {
            if (_sockfd > defaultsockfd)
                ::close(_sockfd);
        }

        bool Recv(std::string *buffer, int size) override
        {
            char inbuffer[size];
            ssize_t n = recv(_sockfd, inbuffer, size - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *buffer += inbuffer;
                return true;
            }
            else
                return false;
        }

        // 默认认为发送成功了
        void Send(std::string &send_string) override
        {
            send(_sockfd, send_string.c_str(), send_string.size(), 0);
        }

        // 端口复用允许TIME_WAIT状态的端口
        void ReUseAddr() override
        {
            int opt = 1;
            setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }

    private:
        int _sockfd;
    };

}